"""
uu_cons表管理器
"""
import time
from typing import Optional, Tuple
from sqlalchemy.exc import SQLAlchemyError
from .models import UuCons
from .sqlalchemy_database import SQLAlchemyDatabaseManager

class ConsManager:
    def __init__(self):
        """初始化管理器"""
        self.db = SQLAlchemyDatabaseManager()
        
    def get_value_with_update_time(self, key: str) -> Tuple[Optional[str], Optional[int]]:
        """
        获取指定key的值和更新时间
        
        Args:
            key: 键名
            
        Returns:
            元组 (值, 更新时间)，如果找不到则返回 (None, None)
        """
        try:
            result = self.db.query(UuCons)\
                .filter(UuCons.conskey == key)\
                .first()
            return (result.consvalue, result.updatet) if result else (None, None)
        except SQLAlchemyError as e:
            print(f"获取配置值时发生错误: {str(e)}")
            return None, None
        
    def get_value(self, key: str) -> Optional[str]:
        """
        获取指定key的值
        
        Args:
            key: 键名
            
        Returns:
            如果找到则返回值，否则返回None
        """
        value, _ = self.get_value_with_update_time(key)
        return value
        
    def set_value(self, key: str, value: str):
        """
        设置指定key的值
        
        Args:
            key: 键名
            value: 值
        """
        current_time = int(time.time())
        session = self.db.get_session()
        
        try:
            cons = session.query(UuCons)\
                .filter(UuCons.conskey == key)\
                .first()
            
            if cons is None:
                # 插入新记录
                cons = UuCons(
                    conskey=key,
                    consvalue=value,
                    createt=current_time,
                    updatet=current_time
                )
                session.add(cons)
            else:
                # 更新现有记录
                cons.consvalue = value
                cons.updatet = current_time
                
            session.commit()
        except SQLAlchemyError as e:
            session.rollback()
            print(f"设置配置值时发生错误: {str(e)}")
        finally:
            session.close()
            
    def delete_value(self, key: str):
        """
        删除指定key的记录
        
        Args:
            key: 键名
        """
        session = self.db.get_session()
        try:
            session.query(UuCons)\
                .filter(UuCons.conskey == key)\
                .delete()
            session.commit()
        except SQLAlchemyError as e:
            session.rollback()
            print(f"删除配置值时发生错误: {str(e)}")
        finally:
            session.close()
